"""
MongoDB 数据库，配置在 settings.py 文件中：
    db='test', host='192.168.1.123', port=27017
"""

from collections import OrderedDict

import mongoengine
from rest_framework.pagination import PageNumberPagination, CursorPagination
from rest_framework.pagination import LimitOffsetPagination

from academic.settings import MONGODB


class Paper(mongoengine.Document):
    """
    paper 类
    """
    meta = {'collection': MONGODB.get('PAPERS')}

    id = mongoengine.StringField(db_field='_id', max_length=50, primary_key=True, required=True)
    title = mongoengine.StringField(max_length=100, required=True)
    authors = mongoengine.ListField(required=False, null=True)
    venue = mongoengine.DictField(required=False, null=True)
    year = mongoengine.IntField(required=False, null=True)
    n_citation = mongoengine.IntField(required=False, null=True)
    page_start = mongoengine.StringField(max_length=10, required=False, null=True)
    page_end = mongoengine.StringField(max_length=10, required=False, null=True)
    lang = mongoengine.StringField(max_length=10, required=False, null=True)
    volume = mongoengine.StringField(max_length=10, required=False, null=True)
    issue = mongoengine.StringField(max_length=10, required=False, null=True)
    url = mongoengine.ListField(required=False, null=True)
    pdf = mongoengine.StringField(max_length=200, required=False, null=True)
    doi = mongoengine.StringField(max_length=200, required=False, null=True)
    keywords = mongoengine.ListField(required=False, null=True)
    abstract = mongoengine.StringField(max_length=5000, required=False, null=True)
    issn = mongoengine.StringField(max_length=100, required=False, null=True)
    isbn = mongoengine.StringField(max_length=30, required=False, null=True)

    def __str__(self):
        return "paper id: " + str(self.id) + "\t titleL: " + str(self.title)


class Venue(mongoengine.Document):
    """
    venue 类
    """
    meta = {'collection': MONGODB.get('VENUES')}

    id = mongoengine.StringField(db_field='_id', max_length=100, primary_key=True)
    display_name = mongoengine.StringField(max_length=100, db_field='DisplayName')
    normalized_name = mongoengine.StringField(max_length=100, db_field='NormalizedName')

    def __str__(self):
        return "venue name: " + str(self.normalized_name)


class Foundation(mongoengine.Document):
    """
    基金类
    """
    meta = {'collection': MONGODB.get('FOUNDATION')}

    id = mongoengine.ObjectIdField(db_field='_id')
    project_num = mongoengine.StringField(db_field='projectNum', max_length='20')
    amount = mongoengine.FloatField(db_field='amount')


class StandardResultSetPagination(PageNumberPagination):
    """
    默认分页
    """
    default_limit = 10
    page_size = 10                 #  每页显示个数
    # max_page_size = 10000        #  最大页数不超过
    page_query_param = "page"
    page_size_query_param = "size"


    # url 中传入的显示数据条数的参数
    # limit_query_param = 'limit'
    # url中传入的数据位置的参数
    # offset_query_param = 'offset'
    # 最大每页显示条数
    # max_limit = None

    # def get_paginated_response(self, data):
    #     """
    #     返回的样式
    #     :param data:
    #     :return:
    #     """
    #     return Response(OrderedDict([
    #         ('next', self.get_next_link()),
    #         ('previous', self.get_previous_link()),
    #         ('results', data)
    #     ]))

    # def get_next_link(self):
    #     if not self.page.has_next():
    #         return None
    #     page_number = self.page.next_page_number()
    #     return replace_query_param('', self.page_query_param, page_number)
    #
    # def get_previous_link(self):
    #     if not self.page.has_previous():
    #         return None
    #     page_number = self.page.previous_page_number()
    #     return replace_query_param('', self.page_query_param, page_number)

class PubsEmbedded(mongoengine.EmbeddedDocument):
    """authors 集合 pubs 嵌入文档"""
    # i 是 Paper 主键，采用懒加载方法
    # 调用 fetch() 方法以获取对象，http://docs.mongoengine.org/apireference.html#mongoengine.fields.LazyReferenceField
    i = mongoengine.LazyReferenceField(document_type=Paper)
    r = mongoengine.IntField(db_field='r')


class TagsEmbedded(mongoengine.EmbeddedDocument):
    """authors 集合 tags 嵌入文档"""
    w = mongoengine.IntField(db_field='w', null=True)
    t = mongoengine.StringField(db_field='t')


class Author(mongoengine.DynamicDocument):
    """
    Author 类
    documents参数介绍：http://docs.mongoengine.org/apireference.html#documents
    """
    # 指定 collection 名字
    # meta = {'collection': MONGODB.get('AUTHORS')}

    id = mongoengine.StringField(db_field='_id', max_length=50, primary_key=True, required=True)
    name = mongoengine.StringField(db_field='name', max_length=30, required=True)
    chiname = mongoengine.StringField(db_field='chiname', max_length=30, required=False, null=True)
    # 头像
    icon = mongoengine.StringField(db_field='icon', required=False, null=True)
    h_index = mongoengine.IntField(db_field='h_index', required=False, null=True)
    """
     "pubs": [
            {
                "i": "55a6921a65ce054aad6c1a31",
                "r": 2
            }
        ]
    pubs 字段是 Array 类型，每个元素又是个 Document
    """
    # pubs = mongoengine.ListField(db_field='pubs')
    pubs = mongoengine.EmbeddedDocumentListField(db_field='pubs', document_type=PubsEmbedded, required=False)
    orgs = mongoengine.ListField(db_field='orgs', required=False, null=True)
    chiorgs = mongoengine.StringField(db_field='chiorgs', required=False, null=True)
    n_pubs = mongoengine.IntField(db_field='n_pubs', required=False, null=True)
    tags = mongoengine.EmbeddedDocumentListField(db_field='tags', document_type=TagsEmbedded, required=False)
    n_citation = mongoengine.IntField(db_field='n_citation', required=False, null=True)
    position = mongoengine.StringField(max_length=20, required=False, null=True)

    def __str__(self):
        return "作者id：" + str(self.id) + "\t 姓名:" + str(self.name)

    meta = {'collection': MONGODB.get('AUTHORS'),
            'indexes': [
                'name'
            ]
            }

# TODO 添加模型
